﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sale.DTO;
using Sale.DTO.ImportExport;

namespace Sale.DataAccess.Repository
{
    public class ImportRepository : BaseRepository
    {
        private MerchandiseRepository _merRepo;

        public ImportRepository()
        {
            _merRepo = new MerchandiseRepository();
        }
        public void AddImportItem(ImportDTO dto)
        {

            var entity = ConvertToEntity(dto);
            Context.Imports.InsertOnSubmit(entity);


        }

        public void DeleteImportItem(Guid id)
        {
            var entity = GetEntity(id);
            Context.Imports.DeleteOnSubmit(entity);
        }

        //public void SetImportItemIsVirtual(Guid importId)
        //{
        //    var entity = GetEntity(importId);
        //    if (entity == null)
        //        throw new ArgumentNullException();
        //    entity.IsVirtual = true;
        //}

        private Import GetEntity(Guid id)
        {
            return Context.Imports.SingleOrDefault(e => e.Id == id);
        }

        //public decimal GetRecordedAverageImportUnitPrice(DateTime from, int merchandiseId)
        //{
        //    AverageImportUnitPrice entity = Context.AverageImportUnitPrices.Where(e => e.FromDate <= from && e.MerchandiseId == merchandiseId)
        //        .OrderByDescending(e => e.FromDate)
        //        .FirstOrDefault();
        //    if (entity == null)
        //        return 0;
        //    return entity.AverageUnitPrice;
        //}

        //public decimal ComputeAverageImportUnitPrice(int month, int year, int merchandiseId)
        //{
        //    if (Context.Imports.Count() == 0)
        //        return 0;
        //    var list = Context.Imports.Where(
        //        e => e.ImportDate.Month == month
        //        && e.ImportDate.Year == year
        //        && e.MerchandiseId == merchandiseId
        //        && !e.IsVirtual);
        //    if (list.Count() == 0)
        //    {

        //        DateTime preMonth = new DateTime(year, month, 1).AddDays(-1);
        //        if (preMonth < DateTime.Now.AddYears(-10))
        //            return 0;
        //        return ComputeAverageImportUnitPrice(preMonth.Month, preMonth.Year, merchandiseId);

        //    }
        //    var value = list.Average(e => e.OriginPrice * e.ExchangeRate);
        //    return value;
        //}

        //public decimal ComputeAverageImportUnitPrice(int month, int year, int merchandiseId)
        //{
        //    var list = Context.Imports.Where(
        //                  e => e.ImportDate.Month == month
        //                  && e.ImportDate.Year == year
        //                  && e.MerchandiseId == merchandiseId
        //                  && !e.IsVirtual);
        //    if (list.Count() > 0)
        //        return list.Average(e => (decimal)e.TotalUnitPrice.Value / (decimal)e.Quantity);
        //    return 0;
        //}

        //public decimal ComputeAverageImportUnitPriceFrom(DateTime from, int merchandiseId)
        //{
        //    var list = Context.Imports.Where(e => e.ImportDate.Date <= from.Date && !e.IsVirtual);
        //    if (list.Count() > 0)
        //        return list.Average(e => (decimal)e.TotalUnitPrice.Value / (decimal)e.Quantity);
        //    return 0;
        //}

        public double GetTotalImportQuantity(DateTime date, int merchandiseId)
        {
            return Context.Imports
                .Where(e => e.ImportDate.Date == date.Date && e.MerchandiseId == merchandiseId)
                .Sum(e => e.Quantity);
        }

        //public void RecordAverageUnitPrice(DateTime from, int merchandiseId, decimal avgPrice)
        //{
        //    var entity = Context.AverageImportUnitPrices.SingleOrDefault(e => e.FromDate.Date == from.Date
        //        && e.MerchandiseId == merchandiseId);
        //    if (entity == null)
        //    {
        //        Context.AverageImportUnitPrices.InsertOnSubmit(new AverageImportUnitPrice()
        //        {
        //            Id = Guid.NewGuid(),
        //            AverageUnitPrice = avgPrice,
        //            FromDate = from,
        //            MerchandiseId = merchandiseId
        //        });
        //    }
        //    else
        //    {
        //        entity.AverageUnitPrice = avgPrice;
        //    }
        //}

        public IEnumerable<ImportDTO> GetImportList(DateTime date)
        {
            return Context.Imports.Where(e => e.ImportDate.Date == date.Date)
                .Select(e => ConvertToDTO(e));
        }

        public IEnumerable<ImportDTO> GetImportList(DateTime from, DateTime to)
        {
            return Context.Imports
                .Where(
                    e => e.ImportDate.Date >= from.Date
                    && e.ImportDate.Date <= to.Date)
                .Select(e => ConvertToDTO(e));
        }

        public IEnumerable<ImportDTO> GetImportListAfter(DateTime time)
        {
            return Context.Imports.Where(e => e.ImportDate >= time)
                .Select(e => ConvertToDTO(e));
        }

        private Import ConvertToEntity(ImportDTO dto)
        {
            return new Import()
            {
                Id = Guid.NewGuid(),
                ImportDate = dto.ImportDate,
                CurrencyId = dto.Currency.Id,
                ExchangeRate = dto.ExchangeRate,
                MerchandiseId = dto.Merchandise.Id,
                OriginPrice = dto.OriginPrice,
                Quantity = dto.Quantity,
                ShippingFee = dto.ShippingFee,
                Tax = dto.Tax,
                Notes = dto.Notes,

                CreatedBy = dto.CreatedBy,
            };
        }

        private ImportDTO ConvertToDTO(Import entity)
        {
            return new ImportDTO()
            {
                Id = entity.Id,
                ImportDate = entity.ImportDate,
                Currency = ObjectMapper.MapSourceToDestination<Currency, CurrencyDTO>(entity.Currency),
                ExchangeRate = entity.ExchangeRate,
                Merchandise = _merRepo.GetMerchandiseById(entity.MerchandiseId),
                OriginPrice = entity.OriginPrice,
                Quantity = entity.Quantity,
                ShippingFee = entity.ShippingFee,
                Tax = entity.Tax,
                //TotalItemValue = entity.un
                Notes = entity.Notes,
                //UnitPriceAfterTax = (decimal)entity.UnitPriceAfterTax,
                //TotalItemValue = (decimal)(entity.UnitPriceAfterTax * entity.Quantity) * entity.ExchangeRate,
                CreatedBy = entity.CreatedBy
            };
        }

    }
}
